package com.dropdb.demo.service.impl;

import com.dropdb.demo.bean.User;
import com.dropdb.demo.bean.UserExample;
import com.dropdb.demo.mapper.UserMapper;
import com.dropdb.demo.service.WxAuthService;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
public class WxAuthServiceImpl implements WxAuthService {

    @Autowired
    UserMapper userMapper;

    @Override
    public boolean isMobileExisted(String mobile) {
        UserExample userExample = new UserExample();
        userExample.createCriteria().andMobileEqualTo(mobile);
        List<User> users = userMapper.selectByExample(userExample);
        if (null != users && 0 < users.size()) {
            return true;
        }
        return false;
    }

    @Transactional
    @Override
    public int register(String username, String password, String mobile) {
        UserExample userExample = new UserExample();
        UserExample.Criteria criteria = userExample.createCriteria().andUsernameEqualTo(username);
        List<User> users = userMapper.selectByExample(userExample);
        if (null != users && 0 < users.size()) { //用户名已被注册
            return -1;
        }

        User user = new User();
        user.setUsername(username);
        //未使用加盐哈希密码
        Md5Hash md5Hash = new Md5Hash(password,user.getUsername(),1);
        String pwd = md5Hash.toHex().toLowerCase();
        user.setPassword(pwd);
        user.setMobile(mobile);
        user.setAddTime(new Date());
        user.setUpdateTime(user.getAddTime());
        user.setDeleted(false);
        user.setUserLevel((byte) 0);
        user.setStatus((byte) 0);
        user.setNickname(user.getUsername());

        return userMapper.insertSelective(user);
    }

    @Override
    public int reset(String mobile, String password) {
        UserExample userExample = new UserExample();
        userExample.createCriteria().andMobileEqualTo(mobile);
        List<User> users = userMapper.selectByExample(userExample);
        if (null == users || 1 != users.size()) {
            return -1;
        }
        User user = users.get(0);
        //未使用加盐哈希密码
        Md5Hash md5Hash = new Md5Hash(password);
        String pwd = md5Hash.toHex().toLowerCase();
        user.setPassword(pwd);
        return userMapper.updateByPrimaryKey(user);
    }

}
